#include "floatconversion.h"

#include <QGroupBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QDebug>
#include <QRegExpValidator>

#include <DLineEdit>

DWIDGET_USE_NAMESPACE
FloatConversion::FloatConversion(QWidget *parent):
    QWidget (parent)
{
    initUi();
    initConnect();
    setEditValidator();
}

FloatConversion::~FloatConversion()
{

}

void FloatConversion::initUi()
{
    m_float = new DLineEdit();
    m_hex = new DLineEdit();
    m_floatToHex = new DPushButton("↓");
    m_hexToFloat = new DPushButton("↑");

    QGroupBox *floatGroup = new QGroupBox(this);
    floatGroup->setTitle("浮点数转换");
    floatGroup->setGeometry(20, 20, 410, 200);

    QLabel *lbFloat = new QLabel("浮点数:    ");
    QLabel *lbHex = new QLabel("十六进制:");

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QHBoxLayout *floatLayout = new QHBoxLayout();
    floatLayout->addWidget(lbFloat);
    floatLayout->addWidget(m_float);
    floatLayout->addWidget(m_floatToHex);

//    QHBoxLayout *btnLayout = new QHBoxLayout();
//    btnLayout->addWidget(m_floatToHex);
//    btnLayout->addWidget(m_hexToFloat);
//    btnLayout->setSpacing(10);

    QHBoxLayout *hexLayout = new QHBoxLayout();
    hexLayout->addWidget(lbHex);
    hexLayout->addWidget(m_hex);
    hexLayout->addWidget(m_hexToFloat);

    mainLayout->addLayout(floatLayout);
    //mainLayout->addLayout(btnLayout);
    mainLayout->addLayout(hexLayout);

    floatGroup->setLayout(mainLayout);
}

void FloatConversion::initConnect()
{
    connect(m_floatToHex, SIGNAL(clicked()), this, SLOT(slotFloatToHex()));
    connect(m_hexToFloat, SIGNAL(clicked()), this, SLOT(slotHexToFloat()));
}

void FloatConversion::setEditValidator()
{
    // 浮点数
    QRegExp rxBinary("[0-9.]*");
    QRegExpValidator *rvBinary = new QRegExpValidator(rxBinary, this);
    m_float->lineEdit()->setValidator(rvBinary);

    // 十六进制
    QRegExp rxHex("[0-9A-Fa-f ]*");
    QRegExpValidator *rvHex = new QRegExpValidator(rxHex, this);
    m_hex->lineEdit()->setValidator(rvHex);
}

QString addSpace(QString str)
{
    int n = str.length();
    while(n-2 > 0)
    {
        n = n - 2;
        str.insert(n," ");
    }

    return str;
}

void FloatConversion::slotFloatToHex()
{
    float f = m_float->text().toFloat();
    int i = *((int *)&f);
    QString hexStr = QString("%1").arg(i, 0, 16, QLatin1Char('0'));
    m_hex->setText(addSpace(hexStr));
}

void FloatConversion::slotHexToFloat()
{
    QString str = m_hex->text();
    int c = str.remove(QRegExp(" ")).toInt(nullptr, 16); //去空格
    float d = *((float*)&c);
    QString radiation = QString("%1").arg(d);

    m_float->setText(radiation);
}

